<template>
  <div>
    <div class="header">
      <span class="iconfont iconjiantou2" @click="goback"></span>
      <div class="search">
        <span class="iconfont iconsearch"></span>
        <input type="text" v-model="keyword" />
      </div>
      <div class="btn" @click="handleSearch">搜索</div>
    </div>

    <div class="historyList" v-if="postList.length == 0">
      <h2>历史记录</h2>
      <div class="list">
        <div @click="historySearch(item)" class="item" v-for="(item, index) in history" :key="index">
          {{ item }}
        </div>
      </div>
    </div>

    <div class="resList">
      <PostItem :postData="post" v-for="post in postList" :key="post.id" />
    </div>
  </div>
</template>

<script>
import PostItem from "../components/PostItem";
export default {
    components: {
      PostItem
    },
  data() {
    return {
      keyword: "",
      postList: [],
      history:[]
    };
  },
  created(){
      //历史记录持久化第二步，如果进入页面时发现本地存储有历史数据，应该回复
      if(localStorage.getItem('history')){
          this.history = JSON.parse(localStorage.getItem('history'));
      }
  },
  watch:{
      keyword(newVal){
          if(!newVal){
              this.postList = [];
          }
      },
      //历史记录持久化第一步，每当数组变化就要存入localStorage
      history(){
          localStorage.setItem('history',JSON.stringify(this.history));
      }
  },
  methods: {
    handleSearch() {
      //拿到当前关键字，发送请求即可
      //点击了搜索应该将当前的keyword添加到历史记录
      this.history.unshift(this.keyword);
      this.$axios({
        url: "post_search",
        params: {
          keyword: this.keyword
        }
      }).then(res => {
        console.log(res.data);
        this.postList = res.data.data;
      });
    },
    goback() {
      if (this.postList.length > 0) {
        this.postList = [];
        this.keyword = "";
      } else {
        this.$router.back();
      }
    },
    historySearch(item){
      this.keyword = item;
      this.handleSearch();

    }
  }
};
</script>

<style lang="less" scoped>
.header {
  display: flex;
  height: 58/360 * 100vw;
  align-items: center;
  padding: 0 16 /360 * 100vw;
  .search {
    flex: 1;
    border: 1px solid #888;
    height: 38/360 * 100vw;
    display: flex;
    align-items: center;
    padding: 0 10/360 * 100vw;
    margin: 0 10/360 * 100vw;
    border-radius: 19/360 * 100vw;
    .iconfont {
      padding-right: 12/360 * 100vw;
      color: #888;
    }
    input {
      width: 180/360 * 100vw;
      border: none;
      outline: none;
    }
  }
  .btn {
    font-size: 16/360 * 100vw;
  }
}

.historyList {
  
  padding: 16/360 * 100vw;
  h2 {
    font-size: 18/360 * 100vw;
  }
  .list {
    padding: 10/360 * 100vw;
    padding-left: 0;
    display: flex;
    flex-wrap:wrap ;
    .item{
      margin:5/360*100vw 10/360*100vw;
    }

  }
}
</style>